package com.nny.alarm.audio;

import com.nny.alarm.R;

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;

public class AudioEffect
{
	public static final int MARK 	= 0;
	public static final int BUTTON 	= 1;
	
	private Context mCtx;
	private SoundPool mSoundPool;
	private int[] mSounds;
	private AudioManager mAudioManager;
	private int mnMaxVolume;
	private boolean mbSilent;
	
	private static AudioEffect mInstance;
	
	public synchronized static AudioEffect getInstance(Context ctx)
	{
		if(null == mInstance)
		{
			mInstance = new AudioEffect(ctx);
		}
		return mInstance;
	}
	
	private AudioEffect(Context ctx)
	{
		mCtx = ctx.getApplicationContext();
		mSounds = new int[2];
		mAudioManager = (AudioManager) mCtx.getSystemService(Context.AUDIO_SERVICE);
		mnMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION);
		mbSilent = false;
	}
	
	private int getCurrentVolume()
	{
		return mAudioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
	}
	
	private float getVolume()
	{
		if(mbSilent)
			return 0.0f;
		return (float)((float)getCurrentVolume() / (float)mnMaxVolume);
	}
	
//	private MediaPlayer mPlayer;
//	private String path;

	public boolean play(int id) {
		
		if(id < 0 || id >= mSounds.length)
			return false;
		
		float v = getVolume();
		mSoundPool.play(mSounds[id], v, v, 0, 0, 1);	
		return true;
	}
	
	public void init()
	{
		mSoundPool = new SoundPool(2, AudioManager.STREAM_NOTIFICATION, 0);
		mSounds[MARK] = mSoundPool.load(mCtx, R.raw.effect_mark, 0);
		mSounds[BUTTON] = mSoundPool.load(mCtx, R.raw.effect_btn, 0);
	}
	
	public void uninit()
	{
		if(null == mSounds)
			return;
		for(int i : mSounds)
		{
			mSoundPool.unload(i);			
		}
	}

	@Override
	protected void finalize() throws Throwable {
		uninit();
	}

}
